package com.nowcoder.community.config;

import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * 一般就是重写三个方法
 * 这里没有重写 认证的方法，绕过了Security的认证，因为想让认证 走我们之前的认证逻辑
 * */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {
    /** 忽略静态资源  */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    /** 2、授权 */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //表示以下路径 是需要登录后才可以访问，以下三个角色登录后 都可以访问
        http.authorizeRequests()
                .antMatchers(
                        "/user/setting",
                        "/user/upload",
                        "/discuss/add",
                        "/comment/add/**",
                        "/letter/**",
                        "/notice/**",
                        "/like",
                        "/follow",
                        "/unfollow"
                )
                .hasAnyAuthority(
                        AUTHORITY_USER,
                        AUTHORITY_ADMIN,
                        AUTHORITY_MODERATOR
                )
                /**以下三个置顶加精删除操作的 权限控制，在前端也做了友好起见，普通用户看不到按钮 */
                .antMatchers(
                        "/discuss/top", //置顶 和 加精
                        "/discuss/wonderful"
                )
                .hasAnyAuthority(
                        AUTHORITY_MODERATOR  //版主
                )
                .antMatchers(
                        "/discuss/delete", //删除帖子 和 统计网站数据
                        "/data/**",
                        "/actuator/**" //管理员才可以访问 项目监控点
                )
                .hasAnyAuthority(
                        AUTHORITY_ADMIN    //管理员
                )
                .anyRequest().permitAll() //其他请求路径 在任何情况下都可以访问
                .and().csrf().disable(); /** 不启动CSRF攻击的检查 */

        // 权限不够时 的处理
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    //没有登录 的处理
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        //请求头的x-requested-with字段 可以知道是 普通请求 还是 异步请求
                        String xRequestedWith = request.getHeader("x-requested-with");
                        //异步请求
                        if ("XMLHttpRequest".equals(xRequestedWith)) {
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "你还没有登录哦!"));
                        } else { //普通请求:跳到登录页面
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
                .accessDeniedHandler(new AccessDeniedHandler() {
                    //权限不足 的处理
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestedWith)) {
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "你没有访问此功能的权限!"));
                        } else {
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                });

        // Security底层默认会拦截/logout请求,进行退出处理。
        // 覆盖它默认的逻辑,才能执行 我们自己的退出代码。
        http.logout().logoutUrl("/securitylogout");
    }

}
